import '@/components/registerNodes';
import G6 from '@antv/g6';
import { Card, Col, Drawer, Row, Select, Space, Statistic } from 'antd';
import { useEffect, useRef, useState } from 'react';
// import NetworkDetails from "./NetworkDetails";
import { useModel, useParams } from 'umi';
import DeviceInfo from './DeviceInfo';
import NetworkQuery from './NetworkQuery';
import { GoldOutlined, ApiOutlined, OrderedListOutlined,InteractionOutlined } from '@ant-design/icons'

export default function HomePage(props) {
  // const {topo, routerToFIB} = props;
  // const { topo, path } = useModel("networkModel");
  const { path } = useModel('networks');
  const { networks } = useModel('networks');
  const [network, setNetwork] = useState({devicesList: [], linksList: []});
  const [graph, setGraph] = useState();
  const containerRef = useRef(null);
  const graphRef = useRef(null);

  const [topo, setTopo] = useState({ nodes: [], edges: [] });
  const [device, setDevice] = useState(null);
  const params = useParams();

  useEffect(() => {
    for (let net of networks) {
      if (net.name == params.name) {
        setNetwork(net);
        let t = { nodes: [], edges: [] };
        for (let dev of net.devicesList) {
          let n = {
            id: dev.name,
            label: dev.name,
            type: dev.type,
          }
          // if (dev.position.x != 0) {
            n.x = dev.position.x;
            n.y = dev.position.y;
          // }
          t.nodes.push(n);
        }
        for (let link of net.linksList) {
          t.edges.push({
            source: link.srcdev,
            target: link.dstdev,
          });
        }
        setTopo(t);
      }
    }
  }, [networks]);

  useEffect(() => {
    console.log(topo);
    if (topo.nodes.length == 0) {
      return;
    }
    if (graph) {
      graph.data(topo);
    }
    const graph = new G6.Graph({
      container: containerRef.current,
      fitView: true,
      height: window.innerHeight - 150,
      fitCenter: true,
      modes: {
        default: ['drag-node', 'drag-canvas', 'zoom-canvas', 'click-select'],
      },
      layout: {
        // type: 'force',
      },
      defaultNode: {
        labelCfg: {
          position: 'bottom',
        },
      },
      defaultEdge: {
        size: 1,
        style: {
          stroke: '#c2c2c2',
          lineAppendWidth: 2,
          // endArrow: true,
        },
      },
      nodeStateStyles: {
        // highlight: {
        //   opacity: 1,
        //   border: 1,
        // },
        // dark: {
        //   opacity: 0.2,
        // },
      },
      edgeStateStyles: {
        // highlight: {
        //   stroke: "#999",
        // },
      },
    });
    setGraph(graph);

    graph.data(topo);
    graph.render();
    graph.zoom(0.75);
    graphRef.current = graph;

    // graph.on('node:click', (ev) => {
    //   const node = ev.item; // 被点击的节点元素
    //   const shape = ev.target; // 被点击的图形，可根据该信息作出不同响应，以达到局部响应效果
    //   console.log(node, shape)
    //   graph.getNodes().forEach(function (node) {
    //     graph.clearItemStates(node);
    //     graph.setItemState(node, 'dark', true);
    //   });
    //   graph.setItemState(node, 'highlight', true);
    //   // setOpen(true)
    // });

    graph.on('node:click', (ev) => {
      setDevice(ev.item);
      console.log(ev.item);
      setOpen(true);
    });

    graph.on('canvas:click', (ev) => {
      setOpen(false);
    });

    // graph.on('canvas:click', (ev) => {
    //   graph.getNodes().forEach(function (node) {
    //     graph.clearItemStates(node);
    //   });
    // });

    graph.changeSize(
      containerRef.current.scrollWidth,
      containerRef.current.scrollHeight,
    );
    if (typeof window !== 'undefined') {
      window.onresize = () => {
        if (!graph || graph.get('destroyed')) return;
        if (
          !containerRef.current ||
          !containerRef.current.scrollWidth ||
          !containerRef.current.scrollHeight
        )
          return;
        graph.changeSize(
          containerRef.current.scrollWidth,
          window.innerHeight - 150,
        );
        // graph.fitCenter();
      };
    }
  }, [topo]);

  const [pathEdges, setPathEdges] = useState([]);

  useEffect(() => {
    const graph = graphRef.current;
    if (!graph) return;
    pathEdges.forEach((arc) => graph.removeItem(arc));
    setPathEdges([]);
    if (path?.length) {
      const pathNodeMap = {};
      let edges = [];
      path.forEach((id, index) => {
        const pathNode = graph.findById(id);
        pathNode.toFront();
        graph.setItemState(pathNode, 'highlight', true);
        pathNodeMap[id] = true;
        if (index < path.length - 1) {
          const arc = graph.addItem('edge', {
            source: id,
            target: path[path.indexOf(id) + 1],
            style: {
              endArrow: true,
              startArrow: false,
            },
          });
          edges.push(arc);
          graph.setItemState(arc, 'highlight', true);
        }
      });
      setPathEdges(edges);
    }
  }, [path]);

  const layout = () => {
    graphRef.current.updateLayout({
      type: 'grid',
      begin: [0, 0],
      preventOverlap: true,
      nodeSize: 100,
    })
  }

  const { Option } = Select;
  const selectBefore = (
    <Select defaultValue="path">
      <Option value="path">Path</Option>
      <Option value="hs">Header</Option>
    </Select>
  );

  const [open, setOpen] = useState(false);

  return (
    // <Card
    //   size="small"
    //   title="LHCONE"
    //   style={{ height: "100%", overflow: "hidden" }}
    // >
    <Space style={{ width: '100%' }} direction="vertical">
      {/* <NetworkDetails topo={topo} routerToFIB={props.routerToFIB} /> */}
      {/* <Input.Search size="large" addonBefore="NQL" defaultValue="" /> */}
      {/* <Space>
          <div>
            From:
            <Select>
              <Option>t1</Option>
            </Select>
          </div>
          <div>
            Header:
            <Select>
              <Option>t1</Option>
            </Select>
          </div>
        </Space> */}
      <Row>
        {/* <Col span={3}>
          <NetworkElementTree />
        </Col> */}
        <Col span={19}>
          <Card size="small" title="Topology" style={{ overflow: 'hidden' }} extra={<a onClick={layout}>Refresh Layout</a>}>
            <div
              ref={containerRef}
              style={{
                background: '#fff',
                border: '0px solid black',
                width: '100%',
                height: '100%',
                minHeight: '100%',
              }}
            ></div>
            <Drawer
              title={device ? device.getID() : ''}
              placement="right"
              closable={false}
              onClose={() => {
                setOpen(false);
              }}
              open={open}
              mask={false}
              getContainer={false}
              rootStyle={{ border: 0 }}
            >
              <DeviceInfo device={device} />
            </Drawer>
          </Card>
        </Col>
        <Col span={5}>
          <Card size="small" title="Information">
            <Row gutter={16}>
              <Col span={12}>
                <Statistic
                  title="#Devices"
                  value={network.devicesList.length}
                  prefix={<GoldOutlined />}
                />
              </Col>
              <Col span={12}>
                <Statistic
                  title="#Links"
                  value={network.linksList.length / 2}
                  prefix={<ApiOutlined />}
                />
              </Col>
              <Col span={12}>
                <Statistic
                  title="#Rules"
                  value={network.numrules}
                  prefix={<OrderedListOutlined />}
                />
              </Col>
              <Col span={12}>
                <Statistic
                  title="#ECs"
                  value={network.numaps}
                  prefix={<InteractionOutlined />}
                />
              </Col>
            </Row>
          </Card>
          <NetworkQuery devices={topo.nodes}/>
          {/* <Path path={cpath} /> */}
        </Col>
      </Row>
    </Space>
    // </Card>
  );
}
